import {hasOwn} from './utils'
import {LIFECYCLE_HOOKS} from '../../shared/constants'

const defaultStrat = function (parentVal, childVal) {
  return childVal === undefined ? parentVal : childVal
}
function mergeHook(parentVal, childVal) {
  const res = childVal
    ? parentVal
      ? parentVal.concat(childVal)
      : Array.isArray(childVal)
      ? childVal
      : [childVal]
    : parentVal
  return res ? dedupeHooks(res) : res
}
function dedupeHooks(hooks) {
  const res = []
  for (let i = 0; i < hooks.length; i++) {
    if (res.indexOf(hooks[i]) === -1) {
      res.push(hooks[i])
    }
  }
  return res
}
let strats = {}
function mergeAssets(parentVal,childVal){
  const res = Object.create(parentVal);
  if(childVal){
    for(let key in childVal){
      res[key] = childVal[key];
    }
  }
  return res;
}
strats.components = mergeAssets;
LIFECYCLE_HOOKS.forEach((hook) => {
  strats[hook] = mergeHook
})
export function mergeOptions(parent, child, vm) {
  const options = {}
  let key
  for (key in parent) {
    mergeField(key)
  }
  for (key in child) {
    if (!hasOwn(parent, key)) {
      mergeField(key)
    }
  }
  function mergeField(key) {
    // 策略模式 strats
    const strat = strats[key] || defaultStrat
    options[key] = strat(parent[key], child[key], vm, key)
  }
  return options
}
